﻿using DbUpgrade.General;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DbUpgrade
{
    public partial class FormChooseDb : Form
    {
        #region 更新脚本链表

        private object _lock_upDbs = new object();
        #endregion

        /// <summary>
        /// 选择的数据库信息
        /// </summary>
        public ChooseDbInfo ChooseDbinfo { get; set; }

        /// <summary>
        /// ip数据库连接
        /// </summary>
        private DalIp _dalIp = null;


        public FormChooseDb()
        {
            InitializeComponent();
        }

        private void RefreshData()
        {
            Task.Run(() =>
            {
                string sql = "select * from DbInfo order by DbChineseName";
                DataTable dt = App.DalData.ExecDataTable(sql);
                lock (_lock_upDbs)
                {
                    List<DbInfo> list = new List<DbInfo>();
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            DbInfo ver = new DbInfo();
                            ver.Id = dr["Id"].ToInt32Ex();
                            ver.DbChineseName = dr["DbChineseName"].ToStringEx();
                            ver.DbKey = dr["DbKey"].ToStringEx();
                            ver.DbCheckName = dr["DbCheckName"].ToStringEx();
                            list.Add(ver);
                        }
                    }
                    this.BeginInvoke(new Action(() =>
                    {
                        viewDbinfo.DataSource = null;
                        viewDbinfo.DataSource = list;
                    }));
                }
            });
        }

        private void FormChooseDb_Load(object sender, EventArgs e)
        {
            viewDbinfo.AutoGenerateColumns = false;
            viewDbIp.AutoGenerateColumns = false;
            RefreshData();
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            if (FormAddDbInfo.ShowAddDbInfo() == DialogResult.OK)
            {
                RefreshData();
            }
        }

        private void viewDbinfo_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }
            if (e.ColumnIndex < 0)
            {
                return;
            }
            DataGridView view = (DataGridView)sender;
            DbInfo m = ((List<DbInfo>)view.DataSource)[e.RowIndex];
            if (view.Columns[e.ColumnIndex].Name == "ColumnDelete")
            {
                if (MessageBox.Show($"是否删除管理库{m.DbChineseName}？", "删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    string password = FormInputPassword.ShowPassword(this);
                    if (password == "jjld2022")
                    {

                        string sql2 = $"DELETE FROM DbInfo where Id = {m.Id}";
                        int i2 = App.DalData.ExecNoQuery(sql2);
                        if (i2 > 0)
                        {
                            RefreshData();
                            try
                            {

                                Thread t = new Thread(new ThreadStart(() =>
                                {
                                    Thread.Sleep(3000);
                                    string dirBase = Path.Combine(CodeHelper.CurrentPath, "data");
                                    string dir = Path.Combine(dirBase, m.DbCheckName);
                                    string dbPath = Path.Combine(dir, "dbupgrade.db");
                                    string dbipPath = Path.Combine(dir, "dbip.db");
                                    if (File.Exists(dbPath))
                                    {
                                        if (App.ChooseDb != null && App.ChooseDb.DbCheckName == m.DbCheckName)
                                        {
                                            App.ChooseDb = null;
                                        }
                                    }
                                    if (File.Exists(dbipPath))
                                    {
                                        if (_dalIp != null)
                                        {
                                            _dalIp.Dal.Dispose();
                                            _dalIp.Dal = null;
                                            _dalIp = null;
                                        }
                                    }

                                    SQLiteConnection.ClearAllPools();
                                    GC.Collect();

                                    int i = 0;
                                    while (true)
                                    {
                                        try
                                        {
                                            i++;
                                            if (i > 100)
                                            {
                                                break;
                                            }
                                            Application.DoEvents();
                                            Thread.Sleep(1000);
                                            if (File.Exists(dbPath))
                                            {
                                                File.Delete(dbPath);
                                            }
                                            if (File.Exists(dbipPath))
                                            {
                                                File.Delete(dbipPath);
                                            }
                                            if (Directory.Exists(dir))
                                            {
                                                Directory.Delete(dir);
                                            }
                                            break;
                                        }
                                        catch (Exception ex)
                                        {
                                            Log.WriteException(ex);
                                        }
                                    }
                                }));
                                t.IsBackground = true;
                                t.Start();

                                MessageBox.Show("删除成功");
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("删除失败,请查看异常。");
                                Log.WriteException(ex);
                            }
                        }
                        else
                        {
                            MessageBox.Show("删除失败");
                        }
                    }
                    else
                    {
                        MessageBox.Show("密码输入错误");
                    }
                }
            }
            else if (view.Columns[e.ColumnIndex].Name == "ColumnAdd")
            {
                if (FormAddDbIp.ShowAddDbIp(m.Id, _dalIp) == DialogResult.OK)
                {
                    RefreshDbIpList();
                }
            }
            else if (view.Columns[e.ColumnIndex].Name == "ColumnEdit")
            {
                //MessageBox.Show("禁止修改");
                if (FormAddDbInfo.ShowEditDbInfo(m.Id) == DialogResult.OK)
                {
                    RefreshData();
                }
            }
        }

        private void viewDbIp_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
                return;
            if (e.ColumnIndex < 0)
                return;
            DataGridView view = (DataGridView)sender;
            DbIp m = ((List<DbIp>)view.DataSource)[e.RowIndex];
            DbInfo dbInfo = GetDbInfoById(m.DbId);
            ChooseDbInfo result = new ChooseDbInfo();
            result.Id = m.Id;
            result.DbId = m.DbId;
            result.DbChineseName = dbInfo.DbChineseName;
            result.DbKey = dbInfo.DbKey;
            result.DbCheckName = dbInfo.DbCheckName;
            result.Ip = m.Ip;
            result.Port = m.Port;
            result.DbName = m.DbName;
            result.UserName = m.UserName;
            result.Password = m.Password;
            ChooseDbinfo = result;
            DialogResult = DialogResult.OK;
        }

        private DbInfo GetDbInfoById(int dbInfoId)
        {
            string sql2 = $"select * from DbInfo where id = {dbInfoId}";
            DataTable dt2 = App.DalData.ExecDataTable(sql2);
            if (dt2 != null && dt2.Rows.Count > 0)
            {
                DataRow dr2 = dt2.Rows[0];
                DbInfo ver2 = new DbInfo();
                ver2.Id = dr2["Id"].ToInt32Ex();
                ver2.DbChineseName = dr2["DbChineseName"].ToStringEx();
                ver2.DbKey = dr2["DbKey"].ToStringEx();
                ver2.DbCheckName = dr2["DbCheckName"].ToStringEx();
                return ver2;
            }
            else
            {
                return null;
            }
        }

        private void viewDbinfo_SelectionChanged(object sender, EventArgs e)
        {
            //if (viewDbinfo.CurrentRow.Index < 0)
            //    return;
            //DataGridView view = (DataGridView)sender;
            //DbInfo m = ((List<DbInfo>)view.DataSource)[viewDbinfo.CurrentRow.Index];
            RefreshDbIpList();
        }

        private void RefreshDbIpList()
        {
            if (viewDbinfo.CurrentRow.Index < 0)
                return;
            DbInfo m = ((List<DbInfo>)viewDbinfo.DataSource)[viewDbinfo.CurrentRow.Index];

            string dirBase = Path.Combine(CodeHelper.CurrentPath, "data");
            string dir = Path.Combine(dirBase, m.DbCheckName);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            string dbipPath = Path.Combine(dir, "dbip.db");
            if (!File.Exists(dbipPath))
            {
                DraftHelper.Instance.ReleaseFile("dbip.db", dir);
            }
            if (_dalIp == null)
            {
                _dalIp = new DalIp();
                _dalIp.Dal = new SqliteDal(dbipPath);
                _dalIp.CheckName = m.DbCheckName;
            }
            else
            {
                if (_dalIp.CheckName != m.DbCheckName)
                {
                    _dalIp.Dal.Dispose();
                    _dalIp.Dal = null;
                    _dalIp = null;

                    _dalIp = new DalIp();
                    _dalIp.Dal = new SqliteDal(dbipPath);
                    _dalIp.CheckName = m.DbCheckName;
                }
            }

            string sql = $"select * from DbIp where DbId = {m.Id}";
            DataTable dt = _dalIp.Dal.ExecDataTable(sql);
            List<DbIp> list = new List<DbIp>();
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    DbIp ver = new DbIp();
                    ver.Id = dr["Id"].ToInt32Ex();
                    ver.DbId = dr["DbId"].ToInt32Ex();
                    ver.Ip = dr["Ip"].ToStringEx();
                    ver.Port = dr["Port"].ToInt32Ex();
                    ver.DbName = dr["DbName"].ToStringEx();
                    ver.UserName = dr["UserName"].ToStringEx();
                    ver.Password = dr["Password"].ToStringEx();
                    list.Add(ver);
                }
            }
            this.BeginInvoke(new Action(() =>
            {
                viewDbIp.DataSource = list;
            }));
        }

        private void viewDbIp_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }
            if (e.ColumnIndex < 0)
            {
                return;
            }
            DataGridView view = (DataGridView)sender;
            DbIp m = ((List<DbIp>)view.DataSource)[e.RowIndex];
            if (view.Columns[e.ColumnIndex].Name == "ColumnDbIpDelete")
            {
                if (MessageBox.Show($"是否删除数据库连接 ip:{m.Ip},dbName:{m.DbName},userName:{m.UserName}？", "删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    string password = FormInputPassword.ShowPassword(this);
                    if (password == "jjld2022")
                    {
                        string sql = $"DELETE FROM DbIp where Id = {m.Id}";
                        int i = _dalIp.Dal.ExecNoQuery(sql);
                        if (i > 0)
                        {
                            MessageBox.Show("删除成功");
                            RefreshDbIpList();
                        }
                        else
                        {
                            MessageBox.Show("删除失败");
                        }
                    }
                    else
                    {
                        MessageBox.Show("密码输入错误");
                    }
                }
            }
            else if (view.Columns[e.ColumnIndex].Name == "ColumnDbIpEdit")
            {
                if (FormAddDbIp.ShowEditDbIp(m.Id, _dalIp) == DialogResult.OK)
                {
                    RefreshDbIpList();
                }
            }
        }
    }
}
